<template>
  <a-layout>
    <a-card title="器材管理" :bordered="false">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <!-- 使用状态列 -->
        <template #usageStatus="{ text }">
          <a-tag :color="text === 0 ? 'blue' : 'green'">
            {{ text === 0 ? '未使用' : '使用中' }}
          </a-tag>
        </template>

        <!-- 器材状态列 -->
        <template #equipmentStatus="{ text }">
          <a-tag :color="getStatusColor(text)">
            {{ getStatusText(text) }}
          </a-tag>
        </template>

        <!-- 图片列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'imageUrl'">
            <a-image :src="record.imageUrl" width="120px" />
          </template>
          <template v-if="column.dataIndex === 'updateTime'">
            {{ dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </template>

        <!-- 操作列 -->
        <template #action="{ record }">
          <a-space>
            <a-button type="link" @click="handleEdit(record)">编辑</a-button>
            <a-button type="link" v-if="record.equipmentStatus === 0" @click="handleCheck(record.id)">检查</a-button>
<!--            <a-button type="link" @click="handleMaintain(record.id)">维护</a-button>-->
            <a-popconfirm
              title="确认删除该器材吗？"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 编辑模态框 -->
    <a-modal
      v-model:visible="editModalVisible"
      title="编辑器材信息"
      @ok="handleEditSubmit"
    >
      <!-- 图片上传组件 -->
      <PictureUpload
        :picture-url="editForm.imageUrl"
        :on-success="handleImageSuccess"
        :category="1"
        style="width: 200px; margin-bottom: 20px"
      />
      <a-form :model="editForm" layout="vertical">
        <a-form-item label="器材名称">
          <a-input v-model:value="editForm.equipmentName" />
        </a-form-item>
        <a-form-item label="价格">
          <a-input-number
            v-model:value="editForm.equipmentPrice"
            :min="0"
            :precision="2"
          />
        </a-form-item>
        <a-form-item label="使用状态">
          <a-select v-model:value="editForm.usageStatus">
            <a-select-option :value="0">未使用</a-select-option>
            <a-select-option :value="1">使用中</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-layout>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import {
  listEquipmentInformationByPageUsingPost,
  deleteEquipmentInformationUsingPost,
  updateEquipmentInformationUsingPost,
  reportEquipmentHealthUsingPost,
} from '@/api/equipmentInformationController.ts';
import dayjs from 'dayjs';
import PictureUpload from '@/components/PictureUpload.vue';
import { addFixEquipmentUsingPost } from '@/api/fixEquipmentController.ts'

const route = useRoute();

// 表格列配置
const columns = [
  { title: '器材名称', dataIndex: 'equipmentName' },
  { title: '价格', dataIndex: 'equipmentPrice' },
  { title: '使用状态', dataIndex: 'usageStatus', slots: { customRender: 'usageStatus' } },
  { title: '器材状态', dataIndex: 'equipmentStatus', slots: { customRender: 'equipmentStatus' } },
  { title: '器材图片', dataIndex: 'imageUrl' },
  { title: '创建时间', dataIndex: 'createTime' },
  { title: '修改时间', dataIndex: 'updateTime' },
  { title: '操作', slots: { customRender: 'action' } },
];

// 数据状态
const tableData = ref([]);
const loading = ref(false);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
});

// 编辑状态
const editModalVisible = ref(false);
const editForm = ref({
  id: null,
  equipmentName: '',
  equipmentPrice: null,
  usageStatus: null,
  equipmentStatus: null,
  imageUrl: '',
});

// 图片上传成功回调
const handleImageSuccess = (picture: API.PictureVO) => {
  editForm.value.imageUrl = picture.url;
};

// 获取设备ID
const equipmentId = ref(null);

// 加载数据
const loadData = async () => {
  try {
    loading.value = true;
    const params = {
      equipmentId: equipmentId.value,
      current: pagination.value.current,
      pageSize: pagination.value.pageSize,
    };
    const res = await listEquipmentInformationByPageUsingPost(params);
    tableData.value = res.data.data.records;
    pagination.value.total = res.data.data.total;
  } catch (error) {
    message.error('数据加载失败');
  } finally {
    loading.value = false;
  }
};

// 处理分页变化
const handleTableChange = (pag) => {
  pagination.value = { ...pagination.value, ...pag };
  loadData();
};

// 处理删除
const handleDelete = async (id) => {
  try {
    await deleteEquipmentInformationUsingPost({ id });
    message.success('删除成功');
    loadData();
  } catch (error) {
    message.error('删除失败');
  }
};

// 处理编辑
const handleEdit = (record) => {
  editForm.value = { ...record };
  editModalVisible.value = true;
};

// 处理检查
const handleCheck = async (id: number) => {
  try {
    await reportEquipmentHealthUsingPost({
      id: id,
      equipmentStatus: 3, // 检查中
    });
    message.success('状态已更新为检查中');
    const res =await addFixEquipmentUsingPost({
      equipmetId: equipmentId.value,
      equipmentInfo: id,
    })
    if(res.data.code === 0){
      message.success('添加维修单成功');
    }else{
      message.error('添加维修单失败');
    }
    loadData();
  } catch (error) {
    message.error('状态更新失败');
  }
};

// 处理报废
// const handleScrap = async (id: number) => {
//   try {
//     await reportEquipmentHealthUsingPost({
//       id: id,
//       equipmentStatus: 2, // 报废
//     })
//     loadData();
//   } catch (error) {
//     message.error('状态更新失败');
//   }
// };

// 处理维护
// const handleMaintain = async (id: number) => {
//   try {
//     await reportEquipmentHealthUsingPost({
//       id: id,
//       equipmentStatus: 4, // 维护中
//     });
//     message.success('状态已更新为维护中');
//     loadData();
//   } catch (error) {
//     message.error('状态更新失败');
//   }
// };

// 修改后的编辑表单提交
const handleEditSubmit = async () => {
  try {
    const params = {
      id: editForm.value.id,
      equipmentName: editForm.value.equipmentName,
      equipmentPrice: editForm.value.equipmentPrice,
      usageStatus: editForm.value.usageStatus,
      imageUrl: editForm.value.imageUrl,
    };
    await updateEquipmentInformationUsingPost(params);
    message.success('更新成功');
    editModalVisible.value = false;
    loadData();
  } catch (error) {
    message.error('更新失败');
  }
};

// 状态文本映射
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '健康';
    case 1:
      return '故障';
    case 2:
      return '报废';
    case 3:
      return '检查中';
    case 4:
      return '维护中';
    default:
      return '未知状态';
  }
};

// 状态颜色映射
const getStatusColor = (status: number) => {
  switch (status) {
    case 0:
      return 'green';
    case 1:
      return 'orange';
    case 2:
      return 'red';
    case 3:
      return 'blue';
    case 4:
      return 'purple';
    default:
      return 'gray';
  }
};

// 初始化
onMounted(() => {
  equipmentId.value = route.query?.equipmentId;
  loadData();
});

// 监听设备ID变化
watch(() => route.query?.equipmentId, (newVal) => {
  equipmentId.value = newVal;
  loadData();
});
</script>
